"""
导入模板库页面

用于导入和管理模板库的页面
"""

import tkinter as tk
from tkinter import ttk, messagebox, filedialog
from pathlib import Path
import sys

# 添加项目根目录到路径
project_root = Path(__file__).parent.parent.parent.parent
sys.path.insert(0, str(project_root))

from src.gui.main_app import BasePage
from src.gui.design_system import (DesignSystem, create_card_frame, 
                                  create_primary_button, create_secondary_button,
                                  create_success_button, create_danger_button)


class ImportTemplatePage(BasePage):
    """导入模板库页面"""
    
    def __init__(self, parent, app):
        super().__init__(parent, app)
        self.import_progress = 0
        self.selected_files = []
        
    def create_page(self):
        """创建页面内容"""
        self.frame = ttk.Frame(self.parent)
        
        # 页面标题
        self.create_header()
        
        # 导入方式选择
        self.create_import_method()
        
        # 文件选择区域
        self.create_file_selection()
        
        # 导入设置
        self.create_import_settings()
        
        # 进度显示
        self.create_progress_display()
        
        # 操作按钮
        self.create_action_buttons()
    
    def create_header(self):
        """创建页面标题"""
        header_frame = ttk.Frame(self.frame)
        header_frame.pack(fill="x", pady=(0, DesignSystem.SPACING['xl']))
        
        # 标题区域
        title_container = ttk.Frame(header_frame)
        title_container.pack(side="left", fill="x", expand=True)
        
        title_label = ttk.Label(
            title_container,
            text="📥 导入模板库",
            style='Title.TLabel'
        )
        title_label.pack(side="left")
        
        # 副标题
        subtitle_label = ttk.Label(
            title_container,
            text="导入剪映模板或自定义模板",
            style='Muted.TLabel'
        )
        subtitle_label.pack(side="left", padx=(DesignSystem.SPACING['md'], 0))
        
        # 返回按钮
        back_btn = create_secondary_button(
            header_frame,
            text="← 返回模板库",
            command=lambda: self.app.show_page("template_library")
        )
        back_btn.pack(side="right")
    
    def create_import_method(self):
        """创建导入方式选择"""
        method_frame = create_card_frame(self.frame, "导入方式")
        method_frame.pack(fill="x", pady=(0, DesignSystem.SPACING['xl']))
        
        # 导入方式选择
        self.import_method_var = tk.StringVar(value="jianying")
        
        # 剪映模板导入
        jianying_frame = ttk.Frame(method_frame)
        jianying_frame.pack(fill="x", pady=(0, DesignSystem.SPACING['md']))
        
        jianying_radio = ttk.Radiobutton(
            jianying_frame,
            text="📱 剪映模板导入",
            variable=self.import_method_var,
            value="jianying",
            command=self.on_method_changed
        )
        jianying_radio.pack(side="left")
        
        jianying_desc = ttk.Label(
            jianying_frame,
            text="导入剪映草稿项目文件 (draft_content.json, draft_meta_info.json)",
            style='Muted.TLabel'
        )
        jianying_desc.pack(side="left", padx=(DesignSystem.SPACING['md'], 0))
        
        # 自定义模板导入
        custom_frame = ttk.Frame(method_frame)
        custom_frame.pack(fill="x", pady=(0, DesignSystem.SPACING['md']))
        
        custom_radio = ttk.Radiobutton(
            custom_frame,
            text="🎨 自定义模板导入",
            variable=self.import_method_var,
            value="custom",
            command=self.on_method_changed
        )
        custom_radio.pack(side="left")
        
        custom_desc = ttk.Label(
            custom_frame,
            text="导入自定义模板文件 (JSON, XML, 或其他格式)",
            style='Muted.TLabel'
        )
        custom_desc.pack(side="left", padx=(DesignSystem.SPACING['md'], 0))
        
        # 批量导入
        batch_frame = ttk.Frame(method_frame)
        batch_frame.pack(fill="x")
        
        batch_radio = ttk.Radiobutton(
            batch_frame,
            text="📦 批量目录导入",
            variable=self.import_method_var,
            value="batch",
            command=self.on_method_changed
        )
        batch_radio.pack(side="left")
        
        batch_desc = ttk.Label(
            batch_frame,
            text="批量导入整个目录下的所有模板文件",
            style='Muted.TLabel'
        )
        batch_desc.pack(side="left", padx=(DesignSystem.SPACING['md'], 0))
    
    def create_file_selection(self):
        """创建文件选择区域"""
        self.file_frame = create_card_frame(self.frame, "文件选择")
        self.file_frame.pack(fill="x", pady=(0, DesignSystem.SPACING['xl']))
        
        # 文件选择按钮区域
        button_row = ttk.Frame(self.file_frame)
        button_row.pack(fill="x", pady=(0, DesignSystem.SPACING['md']))
        
        self.select_file_btn = create_primary_button(
            button_row,
            text="📂 选择文件",
            command=self.select_files
        )
        self.select_file_btn.pack(side="left", padx=(0, DesignSystem.SPACING['sm']))
        
        self.select_folder_btn = create_secondary_button(
            button_row,
            text="📁 选择文件夹",
            command=self.select_folder
        )
        self.select_folder_btn.pack(side="left", padx=(0, DesignSystem.SPACING['sm']))
        
        clear_btn = create_secondary_button(
            button_row,
            text="🗑️ 清空",
            command=self.clear_selection
        )
        clear_btn.pack(side="left")
        
        # 文件列表
        list_container = ttk.Frame(self.file_frame)
        list_container.pack(fill="both", expand=True)
        
        # 创建文件列表
        columns = ('name', 'type', 'size', 'status')
        self.file_tree = ttk.Treeview(list_container, columns=columns, show='headings', height=8)
        
        # 设置列标题
        self.file_tree.heading('name', text='📄 文件名')
        self.file_tree.heading('type', text='🏷️ 类型')
        self.file_tree.heading('size', text='📊 大小')
        self.file_tree.heading('status', text='🔄 状态')
        
        # 设置列宽
        self.file_tree.column('name', width=250, anchor='w')
        self.file_tree.column('type', width=100, anchor='center')
        self.file_tree.column('size', width=100, anchor='center')
        self.file_tree.column('status', width=100, anchor='center')
        
        # 滚动条
        scrollbar = ttk.Scrollbar(list_container, orient="vertical", command=self.file_tree.yview)
        self.file_tree.configure(yscrollcommand=scrollbar.set)
        
        # 布局
        self.file_tree.pack(side="left", fill="both", expand=True)
        scrollbar.pack(side="right", fill="y")
        
        # 空状态提示
        self.create_empty_file_state()
    
    def create_empty_file_state(self):
        """创建空文件状态提示"""
        self.empty_file_frame = ttk.Frame(self.file_frame)
        self.empty_file_frame.place(relx=0.5, rely=0.6, anchor="center")
        
        empty_icon = ttk.Label(
            self.empty_file_frame,
            text="📁",
            font=(DesignSystem.FONTS['family_primary'], 32),
            foreground=DesignSystem.COLORS['text_muted']
        )
        empty_icon.pack()
        
        empty_text = ttk.Label(
            self.empty_file_frame,
            text="请选择要导入的模板文件",
            style='Muted.TLabel'
        )
        empty_text.pack(pady=(DesignSystem.SPACING['sm'], 0))
    
    def create_import_settings(self):
        """创建导入设置"""
        settings_frame = create_card_frame(self.frame, "导入设置")
        settings_frame.pack(fill="x", pady=(0, DesignSystem.SPACING['xl']))
        
        # 第一行：目标分类和覆盖设置
        row1 = ttk.Frame(settings_frame)
        row1.pack(fill="x", pady=(0, DesignSystem.SPACING['md']))
        
        # 目标分类
        category_frame = ttk.Frame(row1)
        category_frame.pack(side="left", fill="x", expand=True, padx=(0, DesignSystem.SPACING['lg']))
        
        ttk.Label(category_frame, text="目标分类:", style='Heading.TLabel').pack(anchor="w")
        self.target_category_var = tk.StringVar(value="默认分类")
        category_combo = ttk.Combobox(
            category_frame,
            textvariable=self.target_category_var,
            values=["默认分类", "剪映模板", "自定义模板", "商业模板", "创意模板"],
            state="readonly",
            width=27
        )
        category_combo.pack(fill="x", pady=(DesignSystem.SPACING['xs'], 0))
        
        # 覆盖设置
        overwrite_frame = ttk.Frame(row1)
        overwrite_frame.pack(side="right", fill="x", expand=True)
        
        ttk.Label(overwrite_frame, text="重复处理:", style='Heading.TLabel').pack(anchor="w")
        self.overwrite_var = tk.StringVar(value="跳过")
        overwrite_combo = ttk.Combobox(
            overwrite_frame,
            textvariable=self.overwrite_var,
            values=["跳过", "覆盖", "重命名", "询问"],
            state="readonly",
            width=27
        )
        overwrite_combo.pack(fill="x", pady=(DesignSystem.SPACING['xs'], 0))
        
        # 第二行：验证和备份选项
        row2 = ttk.Frame(settings_frame)
        row2.pack(fill="x")
        
        # 验证选项
        self.validate_var = tk.BooleanVar(value=True)
        validate_check = ttk.Checkbutton(
            row2,
            text="✅ 导入前验证模板格式",
            variable=self.validate_var
        )
        validate_check.pack(side="left", padx=(0, DesignSystem.SPACING['lg']))
        
        # 备份选项
        self.backup_var = tk.BooleanVar(value=False)
        backup_check = ttk.Checkbutton(
            row2,
            text="💾 创建备份",
            variable=self.backup_var
        )
        backup_check.pack(side="left")
    
    def create_progress_display(self):
        """创建进度显示"""
        self.progress_frame = create_card_frame(self.frame, "导入进度")
        self.progress_frame.pack(fill="x", pady=(0, DesignSystem.SPACING['xl']))
        
        # 进度信息
        info_frame = ttk.Frame(self.progress_frame)
        info_frame.pack(fill="x", pady=(0, DesignSystem.SPACING['md']))
        
        self.progress_label = ttk.Label(info_frame, text="准备就绪", style='Body.TLabel')
        self.progress_label.pack(side="left")
        
        self.progress_detail = ttk.Label(info_frame, text="", style='Muted.TLabel')
        self.progress_detail.pack(side="right")
        
        # 进度条
        self.progress_bar = ttk.Progressbar(
            self.progress_frame,
            mode='determinate',
            length=400
        )
        self.progress_bar.pack(fill="x")
        
        # 初始隐藏进度框
        self.progress_frame.pack_forget()
    
    def create_action_buttons(self):
        """创建操作按钮"""
        button_frame = ttk.Frame(self.frame)
        button_frame.pack(fill="x", pady=DesignSystem.SPACING['xl'])
        
        # 左侧按钮
        left_frame = ttk.Frame(button_frame)
        left_frame.pack(side="left")
        
        validate_btn = create_secondary_button(
            left_frame,
            text="✅ 验证文件",
            command=self.validate_files
        )
        validate_btn.pack(side="left", padx=(0, DesignSystem.SPACING['sm']))
        
        preview_btn = create_secondary_button(
            left_frame,
            text="👁️ 预览导入",
            command=self.preview_import
        )
        preview_btn.pack(side="left")
        
        # 右侧按钮
        right_frame = ttk.Frame(button_frame)
        right_frame.pack(side="right")
        
        cancel_btn = create_secondary_button(
            right_frame,
            text="❌ 取消",
            command=self.cancel_import
        )
        cancel_btn.pack(side="right", padx=(DesignSystem.SPACING['sm'], 0))
        
        self.import_btn = create_success_button(
            right_frame,
            text="📥 开始导入",
            command=self.start_import
        )
        self.import_btn.pack(side="right")
    
    def on_method_changed(self):
        """导入方式改变"""
        method = self.import_method_var.get()
        
        if method == "jianying":
            self.select_file_btn.configure(text="📂 选择剪映文件")
            self.select_folder_btn.configure(text="📁 选择剪映目录")
        elif method == "custom":
            self.select_file_btn.configure(text="📂 选择模板文件")
            self.select_folder_btn.configure(text="📁 选择模板目录")
        else:  # batch
            self.select_file_btn.configure(text="📂 选择文件")
            self.select_folder_btn.configure(text="📁 选择批量目录")
    
    def select_files(self):
        """选择文件"""
        method = self.import_method_var.get()
        
        if method == "jianying":
            file_types = [
                ("剪映文件", "*.json"),
                ("所有文件", "*.*")
            ]
        elif method == "custom":
            file_types = [
                ("模板文件", "*.json *.xml *.yaml"),
                ("所有文件", "*.*")
            ]
        else:
            file_types = [
                ("所有文件", "*.*")
            ]
        
        files = filedialog.askopenfilenames(
            title="选择模板文件",
            filetypes=file_types
        )
        
        if files:
            self.add_files(files)
    
    def select_folder(self):
        """选择文件夹"""
        folder = filedialog.askdirectory(title="选择模板文件夹")
        if folder:
            # 扫描文件夹中的文件
            folder_path = Path(folder)
            files = []
            for file_path in folder_path.rglob("*"):
                if file_path.is_file():
                    files.append(str(file_path))
            
            if files:
                self.add_files(files)
            else:
                messagebox.showwarning("提示", "选择的文件夹中没有找到文件")
    
    def add_files(self, file_paths):
        """添加文件到列表"""
        for file_path in file_paths:
            if file_path not in [f['path'] for f in self.selected_files]:
                file_info = self.get_file_info(file_path)
                self.selected_files.append(file_info)
        
        self.update_file_list()
    
    def get_file_info(self, file_path):
        """获取文件信息"""
        path = Path(file_path)
        size = path.stat().st_size
        
        # 确定文件类型
        ext = path.suffix.lower()
        if ext == '.json':
            file_type = '📄 JSON'
        elif ext == '.xml':
            file_type = '📄 XML'
        elif ext == '.yaml' or ext == '.yml':
            file_type = '📄 YAML'
        else:
            file_type = '📄 其他'
        
        return {
            'path': file_path,
            'name': path.name,
            'type': file_type,
            'size': self.format_file_size(size),
            'status': '⏳ 待导入'
        }
    
    def format_file_size(self, size_bytes):
        """格式化文件大小"""
        if size_bytes == 0:
            return "0 B"
        
        size_names = ["B", "KB", "MB", "GB"]
        i = 0
        size = float(size_bytes)
        
        while size >= 1024.0 and i < len(size_names) - 1:
            size /= 1024.0
            i += 1
        
        return f"{size:.1f} {size_names[i]}"
    
    def update_file_list(self):
        """更新文件列表"""
        # 清空现有项目
        for item in self.file_tree.get_children():
            self.file_tree.delete(item)
        
        # 隐藏/显示空状态
        if self.selected_files:
            self.empty_file_frame.place_forget()
        else:
            self.empty_file_frame.place(relx=0.5, rely=0.6, anchor="center")
            return
        
        # 添加文件项目
        for file_info in self.selected_files:
            self.file_tree.insert('', 'end', values=(
                file_info['name'],
                file_info['type'],
                file_info['size'],
                file_info['status']
            ))
    
    def clear_selection(self):
        """清空选择"""
        self.selected_files.clear()
        self.update_file_list()
    
    def validate_files(self):
        """验证文件"""
        if not self.selected_files:
            messagebox.showwarning("提示", "请先选择文件")
            return
        
        messagebox.showinfo("验证结果", f"验证完成！\n\n有效文件: {len(self.selected_files)}个\n无效文件: 0个")
    
    def preview_import(self):
        """预览导入"""
        if not self.selected_files:
            messagebox.showwarning("提示", "请先选择文件")
            return
        
        preview_info = f"""
导入预览:

导入方式: {self.import_method_var.get()}
目标分类: {self.target_category_var.get()}
重复处理: {self.overwrite_var.get()}
验证格式: {'是' if self.validate_var.get() else '否'}
创建备份: {'是' if self.backup_var.get() else '否'}

待导入文件: {len(self.selected_files)}个
        """
        messagebox.showinfo("导入预览", preview_info.strip())
    
    def start_import(self):
        """开始导入"""
        if not self.selected_files:
            messagebox.showwarning("提示", "请先选择文件")
            return
        
        # 显示进度框
        self.progress_frame.pack(fill="x", pady=(0, DesignSystem.SPACING['xl']))
        
        # 禁用导入按钮
        self.import_btn.configure(state="disabled")
        
        # 模拟导入过程
        self.simulate_import()
    
    def simulate_import(self):
        """模拟导入过程"""
        import threading
        import time
        
        def import_worker():
            total_files = len(self.selected_files)
            
            for i, file_info in enumerate(self.selected_files):
                # 更新进度
                progress = int((i + 1) / total_files * 100)
                
                self.frame.after(0, lambda p=progress, f=file_info['name']: self.update_progress(p, f"正在导入: {f}"))
                
                # 模拟处理时间
                time.sleep(0.5)
                
                # 更新文件状态
                file_info['status'] = '✅ 已导入'
                self.frame.after(0, self.update_file_list)
            
            # 导入完成
            self.frame.after(0, self.import_completed)
        
        thread = threading.Thread(target=import_worker)
        thread.daemon = True
        thread.start()
    
    def update_progress(self, progress, detail):
        """更新进度"""
        self.progress_bar['value'] = progress
        self.progress_label.configure(text=f"导入进度: {progress}%")
        self.progress_detail.configure(text=detail)
    
    def import_completed(self):
        """导入完成"""
        self.progress_label.configure(text="导入完成！")
        self.progress_detail.configure(text=f"成功导入 {len(self.selected_files)} 个模板")
        self.import_btn.configure(state="normal")
        
        messagebox.showinfo("成功", f"模板导入完成！\n\n成功导入: {len(self.selected_files)}个模板")
    
    def cancel_import(self):
        """取消导入"""
        if self.selected_files:
            if messagebox.askyesno("确认", "确定要取消导入吗？"):
                self.app.show_page("template_library")
        else:
            self.app.show_page("template_library")
